//
//  SpaceViewContent.m
//  cutter
//
//  Created by mac on 15/12/21.
//  Copyright © 2015年 e360. All rights reserved.
//
#import "IndexLoginCtrl.h"

//
@implementation IndexLoginCtrl
-(void)viewDidLoad{
    [super viewDidLoad];
    [self.view insertSubview:self.imageView atIndex:0];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    //
    NSString *userName=[[NSUserDefaults standardUserDefaults] valueForKey:@"UserName"];
    NSString *userPass=[[NSUserDefaults standardUserDefaults] valueForKey:@"UserPass"];
    if (isEmpty(userName)==NO && isEmpty(userPass)==NO) {
        [self.nameView setText:base64Decoded(userName)];
        [self.passView setText:base64Decoded(userPass)];
    }
    //logo
    NSString *companyLogo=[[NSUserDefaults standardUserDefaults] valueForKey:@"companyLogo"];
    if (isEmpty(companyLogo)==NO) {
        [AppData loadImage:companyLogo view:self.logoView];
    }
    //背景
    NSString *companyImage=[[NSUserDefaults standardUserDefaults] valueForKey:@"companyImage"];
    if (isEmpty(companyImage)==NO) {
        [AppData loadImage:companyImage view:self.imageView];
    }
}
-(void)keyboardWillShow:(NSNotification *)sender{
    [UIView beginAnimations:nil context:nil];
    [self.planeView setTransform:CGAffineTransformMakeTranslation(0, -220)];
    [UIView commitAnimations];
}
-(void)keyboardWillHide:(NSNotification *)sender{
    [UIView beginAnimations:nil context:nil];
    [self.planeView setTransform:CGAffineTransformIdentity];
    [UIView commitAnimations];
}
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if ([TMGlobal valueForKey:@"user"] == nil) {
        [self loginTouch:nil];
        return NO;
    }
    return YES;
}
-(void)loginTouch:(id)sender{
    [self.view endEditing:YES];
    //
    if (self.nameView.text.length > 0 && self.passView.text.length > 0) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:self.nameView.text forKey:@"username"];
        [dic setValue:self.passView.text forKey:@"password"];
        //
        __weak IndexLoginCtrl *this = self;
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            id data = [AppData userLogin:dic];
            if ([data isKindOfClass:NSDictionary.class]) {
                id company = [data objectForKey:@"company"];
                if (company) {
                    NSString *companyIcon = [company objectForKey:@"icon"];
                    NSString *companyLogo = [company objectForKey:@"logo"];
                    NSString *companyImage = [company objectForKey:@"background"];
                    [TMLoader load:[NSURLRequest requestWithURL:[NSURL URLWithString:[AppData getPath:companyIcon]]] name:companyIcon delegate:nil cache:2];
                    [TMLoader load:[NSURLRequest requestWithURL:[NSURL URLWithString:[AppData getPath:companyLogo]]] name:companyLogo delegate:nil cache:2];
                    [TMLoader load:[NSURLRequest requestWithURL:[NSURL URLWithString:[AppData getPath:companyImage]]] name:companyImage delegate:nil cache:2];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUDForView:this.view animated:YES];
                if ([data isKindOfClass:NSError.class]) {
                    NSError *error = data;
                    [UIAlertController show:nil message:[error.userInfo objectForKey:@"message"] buttons:nil handler:nil];
                }else{
                    id company = [data objectForKey:@"company"];
                    if (company) {
                        /*生成icon
                         UIImage *image = [UIImage imageWithContentsOfFile:[NSString libraryAppend:companyLogo]];
                         if (image) {
                         NSInteger size = MAX(image.size.width, image.size.height);
                         UIImageView *view = [[UIImageView alloc] initWithImage:image];
                         [view setContentMode:UIViewContentModeScaleAspectFit];
                         [view setBackgroundColor:[UIColor whiteColor]];
                         [view setBounds:CGRectMake(0, 0, size, size)];
                         //
                         [self creatLink:companyName icon:[view snapshot]];
                         }*/
                        //
                        [[NSUserDefaults standardUserDefaults] setValue:[company objectForKey:@"background"] forKey:@"companyImage"];
                        [[NSUserDefaults standardUserDefaults] setValue:[company objectForKey:@"shortname"] forKey:@"companyName"];
                        [[NSUserDefaults standardUserDefaults] setValue:[company objectForKey:@"logo"] forKey:@"companyLogo"];
                        [[NSUserDefaults standardUserDefaults] setValue:[company objectForKey:@"icon"] forKey:@"companyIcon"];
                    }
                    [[NSUserDefaults standardUserDefaults] setValue:[self.nameView.text base64Encoded] forKey:@"UserName"];
                    [[NSUserDefaults standardUserDefaults] setValue:[self.passView.text base64Encoded] forKey:@"UserPass"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    //
                    [data setValue:[data objectForKey:@"token"] forKey:@"utoken"];
                    [TMGlobal setValue:data forKey:@"user"];
                    //
                    NSInteger expire = [[data objectForKey:@"date_expire"] integerValue];
                    if (expire != 0) {
                        NSInteger date = [[NSDate dateWithTimeIntervalSince1970:expire] timeIntervalSinceNow];
                        if (date > 0) {
                            [this performSelector:@selector(exitLogin:) withObject:nil afterDelay:date];
                        }
                    }
                    //
                    [this performSegueWithIdentifier:@"loginSegue" sender:sender];
                }
            });
        });
    }else{
        [UIAlertController show:nil message:@"用户名或密码不能为空" buttons:nil handler:nil];
    }
}
-(IBAction)exitLogin:(id)sender{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
//生成外连
-(void)creatLink:(NSString*)name icon:(UIImage*)icon{
    if (icon && name) {
        UIApplication *app = [UIApplication sharedApplication];
        if ([app homeScreenCanAddIcons]) {
            NSString *protocol = @"webLink";
            UIWebClip *clip = [UIWebClip webClipWithIdentifier:protocol];
            [clip setPageURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@://cutter",protocol]]];
            [clip setIconImage:icon isPrecomposed:NO];
            [clip setFullScreen:YES];
            [clip setTitle:name];
            [clip createOnDisk];
            //
            [app addWebClipToHomeScreen:[clip identifier]];
        }
    }
}
@end
